#pragma once
#include <iostream>
#include <unistd.h>
#include <string>

namespace ns_Channel
{
    class Channel
    {
    public:
        Channel(pid_t who, int fd) : _who(who), _fd(fd)
        {
            _name = "我是管道，和" + std::to_string(_who) + "在进行通信，" + "我拥有的写端是: " + std::to_string(_fd);
        }
        ~Channel()
        {
        }

        void Send(int cmd)
        {
            ::write(_fd, &cmd, sizeof(cmd));
        }
        
        void SendName()
        {
            const char *buffer = _name.c_str();
            size_t length = _name.size(); // 获取字符串的实际长度
            ::write(_fd, buffer, length); // 发送字符串内容
        }

        int ID()
        {
            return _who;
        }

        int FD()
        {
            return _fd;
        }

        const std::string &Name()
        {
            return _name;
        }
        void Close()
        {
            close(_fd);
        }

    private:
        pid_t _who; // 记录当前的子进程pid
        int _fd;    // 管道写端
        std::string _name;
    };
}